import { Router } from 'vue-router';
import { TabsState } from '@/renderer/global/tabs';
import { MenuState, MenuItemState } from '@/renderer/global/menu';
import { TabItemState } from '@/renderer/global/tabs';

export class GlobalState {
  /**菜单*/
  menu: MenuState = new MenuState();
  /**标签*/
  tabs: TabsState = new TabsState();
  /**菜单 打开标签*/
  openTabForMenu(menu: MenuItemState, router: Router) {
    // 判断标签是否存在
    let exist = false;
    const tabs = this.tabs.list;
    for (let i = 0; i < tabs.length; i++) {
      if (tabs[i].code === menu.code) {
        exist = true;
        break;
      }
    }
    if (!exist) {
      this.tabs.list.push({
        code: menu.code,
        path: menu.path,
        title: menu.title,
        icon: menu.icon,
        closable: true
      });
    }
    router.replace(menu.path);
    this.menu.default_active = menu.code;
    this.tabs.last_active = this.tabs.default_active;
    this.tabs.default_active = menu.code;
  }
  /**菜单 打开标签*/
  openTabForTabs(tab: TabItemState, router: Router) {
    if (this.tabs.default_active !== tab.code) {
      router.replace(tab.path);
      this.menu.default_active = tab.code;
      this.tabs.last_active = this.tabs.default_active;
      this.tabs.default_active = tab.code;
    }
  }
  /**关闭标签*/
  onCloseTab(tab: TabItemState, router: Router) {
    // 删除点击标签
    for (let i = this.tabs.list.length - 1; i >= 0; i--) {
      if (this.tabs.list[i].code === tab.code) {
        this.tabs.list.splice(i, 1);
      }
    }
    // 判断是否为当前打开的标签
    if (this.tabs.default_active === tab.code) {
      let home = true;
      for (let i = 0; i < this.tabs.list.length; i++) {
        if (this.tabs.list[i].code === this.tabs.last_active) {
          router.replace(this.tabs.list[i].path);
          this.menu.default_active = this.tabs.list[i].code;
          this.tabs.last_active = this.tabs.default_active;
          this.tabs.default_active = this.tabs.list[i].code;
          home = false;
        }
      }
      if (home) {
        router.replace('/');
        this.menu.default_active = '1000';
        this.tabs.default_active = '1000';
      }
    }
  }
}
